package es.us.lsi.aws.api.server;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.us.lsi.aws.api.server.controllers.AccountsController;
import es.us.lsi.aws.api.server.controllers.ExceptionController;
import es.us.lsi.aws.api.server.controllers.MessagesController;

public class ApiServlet extends AbstractServlet {

	private static final long serialVersionUID = -6499210770336659638L;

	// static List<String> allowedResources;
	//
	// static {
	// String[] array = {"messages","scheduling","accounts"};
	// allowedResources = Arrays.asList(array);
	// }

	@Override
	public void process(HttpServletRequest req, HttpServletResponse res) {
		System.out.println(req.getMethod() + " " + req.getPathInfo() + " "
				+ this.getClass().getSimpleName());

		String pathInfo = req.getPathInfo();

		if (pathInfo != null) {
			String[] splittedPathInfo = pathInfo.split("/");
			if (splittedPathInfo.length >= 1) {
				try {
					String firstPath = splittedPathInfo[1];
					if (firstPath.equals("messages")) {
						Controller.processRequestStatic(
								MessagesController.class, req, res);
					} else if (firstPath.equals("accounts")) {
						Controller.processRequestStatic(
								AccountsController.class, req, res);
					} else {
						res.setStatus(HttpServletResponse.SC_NOT_FOUND);
					}
				} catch (Exception e) {
					ExceptionController.processError(req, res, e);
				}
			}
		} else {
			try {
				res.sendRedirect("/");
			} catch (IOException e) {
				ExceptionController.processError(req, res, e);
			}
		}
	}

}
